package cn.edu.swu.syz.controller;

import cn.edu.swu.syz.db.BookResultSetVisitor;
import cn.edu.swu.syz.db.DatabaseService;
import cn.edu.swu.syz.entity.Book;
import cn.edu.swu.syz.utils.HtmlHelper;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.Writer;
import java.sql.SQLException;
import java.util.List;

@WebServlet(urlPatterns = "/books")
public class BookServlet extends HttpServlet {
    // 成员变量：通过单例获取 DatabaseService 实例（正确初始化）
    private DatabaseService service = DatabaseService.getInstance();

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException {
        // 注意：删除了局部变量 service 的定义，直接使用成员变量 service
        try {
            // 直接使用成员变量 service 调用 query 方法
            List<Book> books = service.query(
                    "select * from book", new BookResultSetVisitor());

            response.setContentType("text/html");
            response.setCharacterEncoding("UTF-8");
            try(Writer writer = response.getWriter()) {
                String table = HtmlHelper.buildBooksTable(books);
                String html = HtmlHelper.wrapHtml(table);
                writer.write(html);
                writer.flush();
            }
        } catch (IOException | SQLException e) {
            throw new ServletException(e);
        }
    }
}